define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'filesaver', 'pagination','floatlayer'], function(app) {
    'use strict';
    //客户投诉管理
    app.controller('Complain', function($scope, dataFactoryCRM, $q, $compile, $timeout) {
        $scope.cus = -1;
        $scope.custorme;
        $scope.sign;
        $scope.serperson;
        $scope.create_time;
        $scope.sector_id;
        $scope.shownorhiddenfield = '';
        $scope.state;
        $scope.rd;
        $scope.product;
        $scope.param = {};
        $scope.search_p = { customer: '', content: '', state: -1 };
        $scope.customerpage = { pageAll: 1, pageNow: 1, pageSize: $scope.psize, k: 3 };
        $scope.callingtype = [
            { k: '11', v: '日常事务' },
            { k: '21', v: '广告' },
            { k: '31', v: '投诉' },
            { k: '41', v: '其他' }
        ];
        $scope.statetypes = [
            { k: '0', v: '未处理' },
            { k: '11', v: '处理中' },
            { k: '21', v: '已解决' },
            { k: '31', v: '已挂起' }
        ];

        $scope.customerDataList = function() {
            var listParam = $scope.search_p;
            listParam['psize'] = $scope.customerpage.pageSize;
            listParam['p'] = $scope.customerpage.pageNow;
            var _url = 'Complain/index?' + $.param(listParam) + '&shownorhiddenfield=' + $scope.shownorhiddenfield;
            dataFactoryCRM.getDataByAPI(_url).then(function(_d) {
                if (_d.rcode == 1) {
                    $scope.customerpage.pageSize = _d.psize;
                    $scope.customerpage.pageAll = _d.pall;
                    $scope.customerpage.pageNow = _d.p;
                    $scope.custorme = _d.data;
                } else {
                    $scope.custorme = '';
                    $scope.customerpage.pageAll = 0;
                }
            });
        }
        
        $scope.shownorhiddenrecord = function() {
            dataFactoryCRM.getDataByAPI('Complain/shownorhidden').then(function(_d) {
                $scope.shownorhiddenfield = _d;
                $scope.showorhidden = _d;
                /*$timeout(function() {
                    $scope.customerDataList();
                }, 1000); */
            });
        }
        
         //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.shownorhiddenrecord();
            $scope.customerDataList();
        });

        // edit complain 
        $scope.editComplainBox = function(_d) {
            $("#stateShow>.text").text("请选择处理情况");
            $('#default_state').dropdown('clear');
            $scope.repcontent = '';
            var _vcust = this.vcust;
            //非投诉类型可添加处理情况
            if(_vcust.incoming_type!=31){
                var _url = "Complain/getmessage?id=" + _d;
                dataFactoryCRM.getDataByAPI(_url)
                    .then(function(d) {
                        if (d.from_client != 0) {
                            $scope.rd = true;
                        } else {
                            $scope.rd = false;
                        }
                        $('#Cname1').val(d.customer_name);
                        $('#content1').val(d.content);
                        $('#Ccontact_edit').val(d.customer_phone);
                        if (d.status == 0) {
                            $('#Cstate').val('未处理');
                            $('#default_state').text('处理中');
                            $('#state').val(1);
                        } else if (d.status == 1) {
                            $('#Cstate').val('处理中');
                            $('#default_state').text('处理中');
                            $('#state').val(1);
                        } else if (d.status == 2) {
                            $('#Cstate').val('已解决');
                            $('#default_state').text('已解决');
                            $('#state').val(2);
                        } else {
                            $('#Cstate').val('已挂起');
                            $('#default_state').text('已挂起');
                            $('#state').val(3);
                        }
                        $scope.calltypeedit = d.incoming_type;
                        setTimeout(function() { $('.ui.dropdown').dropdown() }, 50);
                    });
                /**更新成功 */
                function updateSuccess() {
                    setTimeout(function() {
                        $('.modal4').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal4').modal('hide')
                        }, 3000)
                    }, 1000);
                    $scope.customerDataList();
                }
                /**更新失败 */
                function updateFail() {
                    //添加失败了,
                    setTimeout(function() {
                        $('.modal5').modal('show');
                        //3s后关闭
                        setTimeout(function() {
                            $('.modal5').modal('hide')
                        }, 3000)
                    }, 1000);
                     $scope.customerDataList();
                }
                var url = "Complain/getres?id=" + _d;
                dataFactoryCRM.getDataByAPI(url)
                    .then(function(data) {
                        $scope.contentres = data;
                    });
                $('.ui.edit.modal').modal({
                    observeChanges: true,
                    closable:false,
                    onApprove: function() {
                        if ($('#editCustomer').form('is valid')) {
                            dataFactoryCRM.getDataByAPI('Complain/edit?info=' + $scope.repcontent + '&complain_id=' + _d + '&state=' + $('#state').val())
                                .then(function(d) {
                                    if (d['rcode'] == "1") {
                                        updateSuccess();
                                        $scope.shownorhiddenrecord();
                                    } else {
                                        updateFail();
                                        $scope.$emit("NOTBUSY");
                                        $scope.complainMsg = d.msg;
                                    }
                                    $scope.$emit("NOTBUSY");
                                });
                            return true;
                        } else {
                            return false;
                        }
                    }
                }).modal('show');
            }else{
                //投诉类型提示前往风控管理处理
                $('.noEdit').modal('show');
            }
        }

        // click radio event cancle
        $scope.cancle = function() {
            if ($scope.rad == 0) {
                $('#radio').attr("checked", false);
                $scope.rad = 1;
            } else {
                $('#radio').attr("checked", true);
                $scope.rad = 0;
            }

        }

        // click radio event sure
        $scope.sure = function() {
            $('#radio').attr("checked", true);
            $scope.rad = 0;
        }
        $scope.sure();

  

        // add complain records
        $scope.Channal = function() {
            $timeout(function() {
               $('#ChannalID').form('clear'); 
            }, 10);
            
            $('.ui.add.modal').modal({
                closable:false,
                onApprove: function() {
                    if ($('#ChannalID').form('is valid')) {
                        $scope.addChannal($('#ChannalID').serialize());
                        return true;
                    } else
                        return false;
                }
            }).modal('show');
        }

        // add complain records
        $scope.addChannal = function(_d) {
            /**add success */
            function addSuccess() {
                setTimeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
                 $scope.customerDataList();
            }

            function addFail() {
                //添加失败了,
                setTimeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    setTimeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
                 $scope.customerDataList();
            }
            $scope.busy = dataFactoryCRM.postDataByAPI('Complain/add', _d + '&calltypeextra=' + $scope.calltype)
                .then(function(d) {
                    if (d.rcode) {
                        addSuccess();
                        if ($scope.custorme)
                            $scope.custorme.splice(0, 0, d.data);
                        else {
                            $scope.custorme = new Array();
                            $scope.custorme.push(d.data);
                            $scope.customerDataList();
                        }
                        return true;
                    } else {
                        addFail();
                        return false;
                    }
                });
        }

        $scope.$watch('search_p.state', function(oV, nV) {
            if (oV != nV && nV)
                $scope.customerDataList();
        });

        // export records
        $scope.exportRecords = function() {
            var _url = 'Complain/exportRecords?' + $.param($scope.search_p);
            dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
                var blob = new Blob([response], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '客户投诉记录导出表' + '.xls');
            });
        }

        // hidden complain records
        $scope.hideComplainRecord = function(_d) {
            var hiddenId = _d;
            dataFactoryCRM.postDataByAPI('Complain/hideComplainRecord', { hiddeID: hiddenId }).then(function(d) {
                if (d.rcode) {
                    if ($scope.custorme) {
                        $scope.customerDataList();
                    }
                }
            });
        }

        // show complain records
        $scope.showComplainRecord = function(_d) {
            var shownId = _d;
            dataFactoryCRM.postDataByAPI('Complain/showComplainRecord', { showId: shownId }).then(function(d) {
                if (d.rcode) {
                    if ($scope.custorme) {
                        $scope.customerDataList();
                    }
                }
            });
        }
    })
    .directive('incomingType', function( crmParam ) {
            var uTypes = {11:'日常事务',21:'广告',31:'投诉',41:'其他'};
            return {
                restrict: 'A',
                template: "{{type}}",
                link: function(scope, element, attrs) {
                    if (attrs.type&& attrs.type in uTypes)
                        scope.type = uTypes[attrs.type];
                }
            };
     }) 
     .directive('complainStatus', function( crmParam ) {
            var uStatus = {0:'未处理',11:'处理中',21:'已解决',31:'已挂起'};
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status&& attrs.status in uStatus)
                        scope.status =uStatus[attrs.status];
                }
            };
     })
     ;
});